package com.suyafei.controller;

import com.google.code.kaptcha.Producer;
import com.suyafei.enums.BizCodeEnum;
import com.suyafei.enums.SendCodeEnum;
import com.suyafei.service.NotifyService;
import com.suyafei.util.CommonUtil;
import com.suyafei.util.JsonData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @program: suyafei-1024-shop
 * @description
 * @author: luffy
 * @create: 2021-02-22 13:34
 */
@Api(tags = "通知模块")
@RestController
@RequestMapping("/api/user/v1")
@Slf4j
public class NotifyController {
    @Autowired
    private Producer captchaProducer;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 过期时间
     */
    private static final long CAPTCHA_CODE_EXPIRED = 60 * 1000 * 10;

    @Autowired
    private NotifyService notifyService;

    @ApiOperation("验证码")
    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        String captcha = captchaProducer.createText();
        log.info("图形验证码:{}", captcha);

        //存储
        redisTemplate.opsForValue().set(getCaptchaKey(request),captcha,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);

        BufferedImage image = captchaProducer.createImage(captcha);
        ServletOutputStream outputStream = null;
        try {
             outputStream= response.getOutputStream();
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取缓存的key
     * @param request
     * @return
     */
    private String getCaptchaKey(HttpServletRequest request) {
        String ipAddr = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent)");

        String key =  "user-service:captcha:" + CommonUtil.MD5(ipAddr + userAgent);

        log.info("ip={}",ipAddr);
        log.info("userAgent={}", userAgent);
        return key;
    }

    /**
     * 发送验证码
     * 1.匹配图形验证码
     * 2.发送验证码
     *
     * @param to
     * @param captcha
     * @return
     */
    @ApiOperation("发送验证码")
    @GetMapping("send_code")
    public JsonData sendRegisterCode(@ApiParam("收件人") @RequestParam(value = "to", required = true) String to,
                                     @ApiParam("图形验证码") @RequestParam(value = "captcha", required = true) String captcha,
                                     HttpServletRequest request) {
        String key = getCaptchaKey(request);
        String cacheCaptcha = redisTemplate.opsForValue().get(key);
        //匹配图形验证码是否一样
        if (captcha != null && cacheCaptcha != null && captcha.equalsIgnoreCase((cacheCaptcha))) {
            //成功
            redisTemplate.delete(key);
            JsonData jsonData = notifyService.sendCode(SendCodeEnum.USER_REGISTER, to);
            return jsonData;
        }else{
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA);
        }
    }

}
